<route lang="json5" type="page">
{
  style: {
    navigationBarTitleText: '社区',
    navigationBarBackgroundColor: '#f8f8f8',
    navigationBarTextStyle: 'black'
  },
}
</route>

<template>
  <view class="community-container">
    <!-- 顶部发帖入口
    <view class="post-entry">
      <view class="post-entry-content" @click="goToCreatePost">
        <view class="user-avatar">
          <image :src="userStore.userInfo?.avatar || '/static/images/default-avatar.png'" mode="aspectFill" />
        </view>
        <view class="post-input-placeholder">
          <text>分享你的阅读心得...</text>
        </view>
        <view class="post-btn">
          <uni-icons type="compose" size="20" color="#007AFF"></uni-icons>
        </view>
      </view>
    </view> -->

    <!-- 信息流列表 -->
    <scroll-view
      class="scroll-container"
      scroll-y
      refresher-enabled
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
      @scrolltolower="onLoadMore"
      :lower-threshold="100"
    >
      <!-- 空状态 -->
      <view v-if="postList.length === 0 && !loading" class="custom-empty-state">
        <view class="empty-content">
          <view class="empty-icon">
            <uni-icons type="chatbubble" size="64" color="#87ceeb"></uni-icons>
          </view>
          <text class="empty-title">还没有动态哦</text>
          <text class="empty-subtitle">快来分享你的阅读心得吧！</text>
          <!-- <button class="empty-action-btn" @click="goToCreatePost">
            <uni-icons type="plus" size="16" color="#fff"></uni-icons>
            <text class="btn-text">发布第一条动态</text>
          </button> -->
        </view>
      </view>



      <!-- 帖子列表 -->
      <view v-for="post in postList" :key="post.id" class="post-card" @click="goToPostDetail(post.id)">
        <!-- 用户信息区 -->
        <view class="post-header">
          <view class="user-info">
            <image class="user-avatar-small" :src="post.userAvatar || '/static/images/default-avatar.png'" mode="aspectFill" />
            <view class="user-details">
              <text class="user-nickname">{{ post.userNickname }}</text>
              <text class="post-time">{{ formatTime(post.createTime) }}</text>
            </view>
          </view>
          <view class="post-type-badge" v-if="post.type === 'work'">
            <text class="badge-text">{{ post.workType === 'book' ? '绘本' : '绘本集' }}</text>
          </view>
        </view>

        <!-- 作品信息区（仅作品帖显示） -->
        <view v-if="post.type === 'work' && post.workCover" class="work-info" @click.stop="goToWorkDetail(post)">
          <image class="work-cover" :src="post.workCover" mode="aspectFill" />
          <view class="work-details">
            <text class="work-title">{{ post.workTitle }}</text>
            <text class="work-type">{{ post.workType === 'book' ? '绘本作品' : '绘本集' }}</text>
          </view>
          <view class="work-arrow">
            <uni-icons type="right" size="16" color="#999"></uni-icons>
          </view>
        </view>

        <!-- 帖子内容区 -->
        <view class="post-content">
          <text class="post-text" :class="{ 'text-ellipsis': !post.expanded }">{{ post.content }}</text>
          <view v-if="post.content.length > 150" class="expand-btn" @click.stop="toggleExpand(post)">
            <text class="expand-text">{{ post.expanded ? '收起' : '展开' }}</text>
          </view>
        </view>

        <!-- 图片区域 -->
        <view v-if="post.images && post.images.length > 0" class="post-images" @click.stop>
          <view
            v-for="(image, index) in post.images.slice(0, 3)"
            :key="index"
            class="image-item"
            :class="getImageClass(post.images.length)"
            @click="previewImages(post.images, index)"
          >
            <image :src="image" mode="aspectFill" />
            <view v-if="index === 2 && post.images.length > 3" class="more-images-overlay">
              <text class="more-count">+{{ post.images.length - 3 }}</text>
            </view>
          </view>
        </view>

        <!-- 互动区域 -->
        <view class="post-actions">
          <view class="action-item" :class="{ 'liking': post.isLiking }" @click.stop="toggleLike(post)">
            <uni-icons
              v-if="!post.isLiking"
              :type="post.isLiked ? 'heart-filled' : 'heart'"
              :color="post.isLiked ? '#ff4757' : '#999'"
              size="18"
            ></uni-icons>
            <uni-icons
              v-else
              type="spinner-cycle"
              color="#ff4757"
              size="18"
            ></uni-icons>
            <text class="action-text" :class="{ 'liked': post.isLiked, 'liking': post.isLiking }">{{ formatLikeCount(post.likeCount) }}</text>
          </view>
          <view class="action-item" @click.stop="goToPostDetail(post.id)">
            <uni-icons type="chat" color="#999" size="18"></uni-icons>
            <text class="action-text">{{ formatCommentCount(post.commentCount) }}</text>
          </view>
          <!-- <view class="action-item">
            <uni-icons type="redo" color="#999" size="18"></uni-icons>
            <text class="action-text">分享</text>
          </view> -->
        </view>
      </view>

      <!-- 加载更多状态 -->
      <view v-if="postList.length > 0" class="load-more-status">
        <view v-if="loadingMore" class="loading-text">
          <uni-icons type="spinner-cycle" size="16" color="#999"></uni-icons>
          <text>加载中...</text>
        </view>
        <view v-else-if="noMoreData" class="no-more-text">
          <text>暂无更多数据</text>
        </view>
      </view>
    </scroll-view>



    <!-- 右下角悬浮发帖按钮 -->
    <view class="floating-add-btn" @click="goToCreatePost">
      <view class="add-btn-content">
        <wd-icon name="add" size="20px" color="#fff"></wd-icon>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { getCommunityPosts, togglePostLike, type PostRespVO } from '@/api/community'
import { formatRelativeTime } from '@/utils/time'

// 帖子列表
const postList = ref<(PostRespVO & { expanded?: boolean; isLiking?: boolean })[]>([])

// 分页相关状态
const currentPage = ref(1)
const pageSize = ref(20)
const loading = ref(false)
const refreshing = ref(false)
const loadingMore = ref(false)
const noMoreData = ref(false)

// 标记是否首次加载
const isFirstLoad = ref(true)

// 加载帖子列表
async function loadPostList(isRefresh = false) {
  if (loading.value || (loadingMore.value && !isRefresh)) return

  try {
    if (isRefresh) {
      currentPage.value = 1
      noMoreData.value = false
    } else {
      loadingMore.value = true
    }

    loading.value = true

    console.log('开始加载帖子列表，页码:', currentPage.value, '页大小:', pageSize.value)

    const response = await getCommunityPosts({
      pageNo: currentPage.value,
      pageSize: pageSize.value
    })

    console.log('API响应:', response)

    if (response.code === 0 && response.data) {
      const responseData = response.data as any
      console.log('响应数据:', responseData)

      // 检查数据结构
      if (responseData.list && Array.isArray(responseData.list)) {
        const posts = responseData.list.map((post: any) => ({
          ...post,
          expanded: false // 添加展开状态
        }))

        console.log('处理后的帖子列表:', posts)
        console.log('当前页数据长度:', posts.length, '页大小:', pageSize.value)

        // 更新帖子列表
        if (isRefresh || currentPage.value === 1) {
          postList.value = posts
        } else {
          postList.value.push(...posts)
        }

        // 检查是否还有更多数据
        if (posts.length < pageSize.value) {
          noMoreData.value = true
        } else {
          currentPage.value++
        }

        console.log('更新后postList长度:', postList.value.length)
      } else {
        console.warn('数据格式不正确，没有list字段或list不是数组')
        if (isRefresh || currentPage.value === 1) {
          postList.value = []
        }
      }
    } else {
      console.warn('获取社区帖子失败:', response.msg)
      if (isRefresh || currentPage.value === 1) {
        postList.value = []
      }
      uni.showToast({
        title: response.msg || '加载失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('加载社区帖子失败:', error)
    uni.showToast({
      title: '加载失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
    loadingMore.value = false
    refreshing.value = false
  }
}

// 下拉刷新
async function onRefresh() {
  refreshing.value = true
  await loadPostList(true)
}

// 上拉加载更多
async function onLoadMore() {
  if (!noMoreData.value && !loadingMore.value) {
    await loadPostList(false)
  }
}

// 格式化时间
function formatTime(timeStr: string) {
  return formatRelativeTime(timeStr)
}

// 格式化点赞数量
function formatLikeCount(count: number | undefined | null): string {
  if (!count || count === 0) {
    return '点赞'
  }

  if (count < 1000) {
    return count.toString()
  } else if (count < 10000) {
    return (count / 1000).toFixed(1) + 'k'
  } else {
    return (count / 10000).toFixed(1) + 'w'
  }
}

// 格式化评论数量
function formatCommentCount(count: number | undefined | null): string {
  if (!count || count === 0) {
    return '评论'
  }

  if (count < 1000) {
    return count.toString()
  } else if (count < 10000) {
    return (count / 1000).toFixed(1) + 'k'
  } else {
    return (count / 10000).toFixed(1) + 'w'
  }
}

// 切换点赞状态
async function toggleLike(post: PostRespVO & { expanded?: boolean; isLiking?: boolean }) {
  // 防止重复点击
  if (post.isLiking) {
    return
  }

  try {
    // 标记正在点赞，防止重复点击
    post.isLiking = true

    // 乐观更新UI，提供即时反馈
    const originalIsLiked = post.isLiked
    const originalLikeCount = post.likeCount

    post.isLiked = !originalIsLiked
    post.likeCount = originalIsLiked ? originalLikeCount - 1 : originalLikeCount + 1

    // 调用API
    const response = await togglePostLike(post.id)

    if (response.code === 0 && response.data) {
      const data = response.data as any
      // 使用服务器返回的真实数据更新UI
      post.isLiked = data.isLiked
      post.likeCount = data.likeCount
    } else {
      // API调用失败，回滚UI状态
      post.isLiked = originalIsLiked
      post.likeCount = originalLikeCount
      throw new Error(response.msg || '点赞失败')
    }
  } catch (error) {
    console.error('点赞操作失败:', error)

    // 确保UI状态回滚
    const originalIsLiked = !post.isLiked
    const originalLikeCount = post.isLiked ? post.likeCount + 1 : post.likeCount - 1
    post.isLiked = originalIsLiked
    post.likeCount = originalLikeCount

    uni.showToast({
      title: error instanceof Error ? error.message : '操作失败',
      icon: 'none',
      duration: 2000
    })
  } finally {
    // 清除点赞状态标记
    post.isLiking = false
  }
}

// 切换内容展开状态
function toggleExpand(post: PostRespVO & { expanded?: boolean; isLiking?: boolean }) {
  post.expanded = !post.expanded
}

// 获取图片样式类
function getImageClass(imageCount: number) {
  if (imageCount === 1) return 'single-image'
  if (imageCount === 2) return 'double-image'
  return 'triple-image'
}

// 预览图片
function previewImages(images: string[], current: number) {
  uni.previewImage({
    urls: images,
    current: current
  })
}

// 跳转到发帖页面
function goToCreatePost() {
  uni.navigateTo({
    url: '/pages-sub/community/create-post/index'
  })
}



// 跳转到帖子详情
function goToPostDetail(postId: number) {
  uni.navigateTo({
    url: `/pages-sub/community/post-detail/index?id=${postId}`
  })
}

// 跳转到作品详情
function goToWorkDetail(post: PostRespVO & { expanded?: boolean; isLiking?: boolean }) {
  if (post.workType === 'book') {
    // 跳转到绘本阅读器
    uni.navigateTo({
      url: `/pages-sub/reading/picture-book-reader/index?bookId=${post.workId}`
    })
  } else if (post.workType === 'bookset') {
    // 跳转到绘本集详情
    uni.navigateTo({
      url: `/pages-sub/reading/picture-book-set/index?id=${post.workId}`
    })
  }
}

onLoad(() => {
  console.log('社区页面加载完成')
  // 首次加载数据
  loadPostList(true)
})

onShow(() => {
  console.log('社区页面显示')

  // 只在非首次加载时刷新数据，避免重复加载
  if (!isFirstLoad.value) {
    console.log('触发数据刷新')
    loadPostList(true)
  } else {
    console.log('首次加载，跳过刷新')
    isFirstLoad.value = false
  }
})
</script>

<style lang="scss" scoped>
@import '@/styles/variables.scss';

.community-container {
  background: $bg-gradient;
  min-height: 100vh;
  position: relative;
}

.scroll-container {
  height: 100vh;
  padding: $container-padding;
  padding-top: 20px;
  box-sizing: border-box;
}

.post-entry {
  background: $white;
  // margin: $container-padding;
  border-radius: $border-radius-xl;
  box-shadow: $shadow-sm;
  
  .post-entry-content {
    display: flex;
    align-items: center;
    padding: 15px;
    gap: 12px;
    
    .user-avatar {
      width: 36px;
      height: 36px;
      border-radius: 50%;
      overflow: hidden;
      
      image {
        width: 100%;
        height: 100%;
      }
    }
    
    .post-input-placeholder {
      flex: 1;
      background: $gray-100;
      padding: 10px 15px;
      border-radius: 20px;
      
      text {
        color: $gray-500;
        font-size: 14px;
      }
    }
    
    .post-btn {
      padding: 8px;
    }
  }
}

.post-card {
  background: $white;
  margin-bottom: $container-padding;
  border-radius: $border-radius-xl;
  box-shadow: $shadow-sm;
  overflow: hidden;
}

.post-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px 15px 0;
  
  .user-info {
    display: flex;
    align-items: center;
    gap: 10px;
    
    .user-avatar-small {
      width: 44px;
      height: 44px;
      border-radius: 50%;
    }
    
    .user-details {
      display: flex;
      flex-direction: column;
      gap: 2px;
      
      .user-nickname {
        font-size: 14px;
        font-weight: 600;
        color: $dark-gray;
      }

      .post-time {
        font-size: 12px;
        color: $medium-gray;
      }
    }
  }
  
  .post-type-badge {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    padding: 4px 8px;
    border-radius: 10px;
    
    .badge-text {
      color: $white;
      font-size: 10px;
      font-weight: 600;
    }
  }
}

.work-info {
  display: flex;
  align-items: center;
  margin: 10px 15px;
  padding: 10px;
  background: $gray-100;
  border-radius: $border-radius-lg;
  gap: 10px;
  
  .work-cover {
    width: 40px;
    height: 40px;
    border-radius: $border-radius-sm;
  }
  
  .work-details {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 2px;
    
    .work-title {
      font-size: 13px;
      font-weight: 600;
      color: $dark-gray;
    }

    .work-type {
      font-size: 11px;
      color: $medium-gray;
    }
  }
}

.post-content {
  padding: 10px 15px;
  
  .post-text {
    font-size: 14px;
    line-height: 1.6;
    color: $dark-gray;
    
    &.text-ellipsis {
      display: -webkit-box;
      -webkit-line-clamp: 3;
      line-clamp: 3;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }
  }
  
  .expand-btn {
    margin-top: 5px;
    
    .expand-text {
      color: $primary-blue;
      font-size: 13px;
    }
  }
}

.post-images {
  display: flex;
  gap: 4px;
  padding: 0 15px 10px;
  
  .image-item {
    position: relative;
    border-radius: $border-radius-sm;
    overflow: hidden;
    
    &.single-image {
      width: 100%;
      height: 200px;
    }
    
    &.double-image {
      width: calc(50% - 2px);
      height: 120px;
    }
    
    &.triple-image {
      width: calc(33.33% - 3px);
      height: 100px;
    }
    
    image {
      width: 100%;
      height: 100%;
    }
    
    .more-images-overlay {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.6);
      display: flex;
      align-items: center;
      justify-content: center;
      
      .more-count {
        color: $white;
        font-size: 16px;
        font-weight: 600;
      }
    }
  }
}

.post-actions {
  display: flex;
  align-items: center;
  padding: 10px 15px 15px;
  gap: 30px;
  
  .action-item {
    display: flex;
    align-items: center;
    gap: 5px;
    transition: all 0.3s ease;

    &.liking {
      opacity: 0.7;
      transform: scale(0.95);
    }

    .action-text {
      font-size: 12px;
      color: $medium-gray;
      transition: color 0.3s ease;

      &.liked {
        color: #ff4757;
      }

      &.liking {
        color: #ff4757;
      }
    }
  }
}

.floating-add-btn {
  position: fixed;
  right: 25px;
  bottom: 100px; // 避免与底部导航栏重叠
  z-index: $z-index-docked;

  .add-btn-content {
    width: 56px;
    height: 56px;
    background: linear-gradient(135deg, $primary-blue 0%, $sky-blue 100%);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: $shadow-lg;
    transition: all 0.3s ease;

    &:active {
      transform: scale(0.95);
      box-shadow: $shadow-md;
    }
  }
}

// 自定义空状态样式
.custom-empty-state,
.backup-empty-state {
  padding: 80px 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

.empty-content {
  text-align: center;
  max-width: 280px;

  .empty-icon {
    margin-bottom: 24px;
    opacity: 0.8;
  }

  .empty-title {
    display: block;
    font-size: 18px;
    font-weight: 600;
    color: $dark-gray;
    margin-bottom: 12px;
  }

  .empty-subtitle {
    display: block;
    font-size: 14px;
    color: $medium-gray;
    line-height: 1.5;
    margin-bottom: 32px;
  }

  .empty-action-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    padding: 12px 24px;
    background: linear-gradient(135deg, $primary-blue 0%, $sky-blue 100%);
    border: none;
    border-radius: 24px;
    box-shadow: 0 4px 16px rgba(66, 187, 255, 0.3);
    transition: all 0.3s ease;

    &:active {
      transform: translateY(1px);
      box-shadow: 0 2px 8px rgba(66, 187, 255, 0.4);
    }

    .btn-text {
      color: $white;
      font-size: 14px;
      font-weight: 600;
    }
  }
}

// 加载更多状态样式
.load-more-status {
  padding: 20px;
  text-align: center;

  .loading-text {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    color: $medium-gray;
    font-size: 14px;
  }

  .no-more-text {
    color: $medium-gray;
    font-size: 14px;
  }
}

</style>
